-- Globals Section
JustInTime_UpdateInterval = 2.5; -- How often the OnUpdate code will run (in seconds)
JustInTime_PlaceCount = 0;

function out(text)
 DEFAULT_CHAT_FRAME:AddMessage(text)
 UIErrorsFrame:AddMessage(text, 1.0, 1.0, 0, 1, 10) 
end

function JustInTime_Toggle()
   local frame = getglobal("JustInTimeFrame")
   if (frame) then
   	if(  frame:IsVisible() ) then
		frame:Hide();
   	else
		JustInTime_PlaceCount = 0;
      	frame:Show();
   	end
   end
end

function JustInTime_OnLoad()
	out("JustInTime: OnLoad");
	SlashCmdList["JUSTINTIME"] = JustInTime_SlashCommandHandler;
	SLASH_JUSTINTIME1 = "/justintime";
	SLASH_JUSTINTIME2 = "/jit";
end

function JustInTime_SlashCommandHandler()
    out("JustInTime: SlashCommandHandler")
 	JustInTime_Toggle();
end

function JustInTime_OnUpdate(self, elapsed)
  self.TimeSinceLastUpdate = self.TimeSinceLastUpdate + elapsed; 	

  while (self.TimeSinceLastUpdate > JustInTime_UpdateInterval) do
   	self.TimeSinceLastUpdate = self.TimeSinceLastUpdate - JustInTime_UpdateInterval;
	--print(JustInTime_PlaceCount);
	JustInTime_Invite();
	JustInTime_PlaceCount = JustInTime_PlaceCount + 1;
  end
end

function JustInTime_Invite()
	--out("JustInTime:Invite");
	if (JustInTime_PlaceCount < GetNumGuildMembers(true)+1) then
		--out("JustInTime:Not Done");
		test,test2=GetGuildRosterInfo(JustInTime_PlaceCount);
		--print(test .. ":" .. test2);
   		years,months,days,hours=GetGuildRosterLastOnline(JustInTime_PlaceCount);
   		years, months, days, hours = years and years or 0, months and months or 0, days and days or 0, hours and hours or 0;
   		toff = (((years*12)+months)*30.5+days)*24+hours;
		if ((test2 == "Milites" or test2 == "Tribuni" or test2 == "Procurator" or test2 == "Praefectus" or test2 == "Guard" or test2 == "Citizen" or test2 == "Initiate") and not(test == "Pgraidbank") and (toff < 720))  then
			print(test .. ':' .. test2 .. ":" .. toff/24); 
      		CalendarEventInvite(test);
		end
	else
		out('JustInTime: Done');
		JustInTime_Toggle();
	end
end